
#include "os_taskm.h"

OS_TaskControlBlockType * __far OS_TaskControlBlock;

OS_QueueType * __far OS_Queue;

OS_TaskType ActualTaskID;

OS_StatusType TerminateTask(void){
	//OS_StatusType rvalue;
	uint8_t priorityTemp;
	uint8_t u8counter;
	OS_StatusType Status;
	OS_TaskType taskID;
	/*Get Task ID*/
	Status = GetTaskID(&taskID);
	/* Get the priority of the actual running task */
	priorityTemp = OS_TaskControlBlock[taskID].Priority;
	/* Remove the task from  the QUEUE */
	u8counter = 0;
	while(OS_Queue[priorityTemp].Queue[u8counter] != taskID){u8counter++;}
	OS_Queue[priorityTemp].Queue[u8counter] = NONE;
	OS_Queue[priorityTemp].u8QueueDepth--;
	OS_TaskControlBlock[taskID].State=SUSPENDED;
	ActualTaskID = NONE;
	if(OS_Queue[priorityTemp].u8QueueDepth == 0){
		OS_Queue[priorityTemp].u8index=0;
	}

	return E_OK;
}

OS_StatusType ActivateTask(OS_TaskType taskID){
	OS_StatusType rvalue;
	uint8_t priorityTemp;
	/* check if it is a valid ID */
	if(taskID >= NONE){
		/* if it is not correct return E_OS_ID */
		rvalue = E_OS_ID;
	} else{
		/* Get the priority */
		priorityTemp = OS_TaskControlBlock[taskID].Priority;
		/* if it is a valid ID check for queue limit */
		if(OS_Queue[priorityTemp].u8QueueDepth >= OS_MAX_QUEUE_SIZE){
			/* The queue reach the limit */
			rvalue = E_OS_LIMIT;
		}
		else{
			OS_TaskControlBlock[taskID].State= READY;
			OS_Queue[priorityTemp].Queue[OS_Queue[priorityTemp].u8index] = taskID;
			OS_Queue[priorityTemp].u8index++;
			OS_Queue[priorityTemp].u8QueueDepth++;
			rvalue = E_OK;
		}
	}
	return rvalue;
}

OS_StatusType GetTaskID(OS_TaskRefType taskIDRef){
	*taskIDRef = ActualTaskID;
	return E_OK;
}

OS_StatusType GetTaskState(OS_TaskType taskID, OS_TaskStateRefType stateRef ){
	*stateRef = OS_TaskControlBlock[taskID].State;
	return E_OK;
}